package com.glodon.paas.exception.i18n;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.glodon.paas.exception.PaasServerException;
import com.glodon.paas.util.PropertyUtil;

public class PropertyMessage implements Message {
	
	public static final Logger LOGGER = LoggerFactory.getLogger(PropertyMessage.class);
	
	private static Map<Locale, Map<String, String>> infoMap = new HashMap<Locale, Map<String,String>>();
	
	private static Locale defauleLocale = new Locale("zh", "CN"); 
	
	private String getText(Locale locale, int code) {
		if(!infoMap.containsKey(locale)){
			infoMap.put(locale, PropertyUtil.convertFileToMap("i18n/errorCode_"+locale.getLanguage()+"_"+locale.getCountry()));
		}
		Map<String, String> localeMap = infoMap.get(locale);
		if (localeMap.containsKey(String.valueOf(code))) {
			return (String) localeMap.get(String.valueOf(code));
		} else {
			return String.valueOf(code);
		}
	}

	private String getText(Locale locale, int code, List<String> args) {
		String value = getText(locale, code);
		for(int i=0; i<args.size(); i++){
			value = value.replaceAll("{"+i+"}", args.get(i));
		}
		return value;
	}

	@Override
	public String getText(PaasServerException e) {
		return getText(e, defauleLocale);
	}
	
	@Override
	public String getText(PaasServerException e,Locale locale) {
		String text;
		if(e.getObjs()==null || e.getObjs().size()==0){
			text = getText(locale,e.getErrorCode());
		}
		else{
			text = getText(locale,e.getErrorCode(), e.getObjs());
		}
		
		if(text.equals(String.valueOf(e.getErrorCode()))){
			return e.getMessage();
		}
		else{
			return text;
		}
	}
}
